using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.IdentityModel.Logging;

using System.IdentityModel.Tokens.Jwt;

using Web.Mvc.Helper;
using Web.MVC.Helper;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
IdentityModelEventSource.ShowPII = true;
IdentityModelEventSource.LogCompleteSecurityArtifact = true;
builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "oidc";
})
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, x =>
    {
        x.LogoutPath = "/Login";
    })
        .AddOpenIdConnect("oidc", options =>
        {

            options.Authority = builder.Configuration.GetValue<string>("AuthorityAddress"); //
                                                                                            //  options.MetadataAddress = builder.Configuration.GetValue<string>("AuthorityAddress") + ".well-known/openid-configuration";

            options.ClientId = "webclient";
            options.ClientSecret = "webclient";
            options.ResponseType = "code";

            options.RequireHttpsMetadata = false;

            options.SaveTokens = true;
            options.SignedOutCallbackPath = "/Login/LoginOut";
            //  options.TokenValidationParameters.ValidateIssuer = false;

            //必须设置cookie signin-oidc 返回的cookie设置，这里是添加的代码//http不能登录
            //options.CorrelationCookie.SecurePolicy = CookieSecurePolicy.None;
            //options.NonceCookie.SecurePolicy = CookieSecurePolicy.None;
            //options.CorrelationCookie.SameSite = SameSiteMode.Strict;
            //options.NonceCookie.SameSite = SameSiteMode.Strict;
            //options.Scope.Clear();
            // options.Scope.Add("api1");
            //options.Scope.Add("orderApiScope");
            //options.Scope.Add("productApiScope");
            options.Scope.Add("orderScope");
            options.Scope.Add("productScope");

            // options.AccessDeniedPath = "/Authorization/AccessDenied";
            //options.Scope.Add(OidcConstants.StandardScopes.OpenId);
            //options.Scope.Add(OidcConstants.StandardScopes.Profile);
            //options.Events = new OpenIdConnectEvents
            //{
            //    OnAuthenticationFailed = context =>
            //    {
            //        context.HandleResponse();
            //        context.Response.WriteAsync("验证失败");
            //        return Task.CompletedTask;
            //    }
            //};



        });
builder.Services.AddSingleton<IServiceHelper, GatewayServiceHelper>();

builder.Services.AddHttpClient();


//解决AuthenticationFailureException: Correlation failed. Unknown location？？？
builder.Services.Configure<CookiePolicyOptions>(option =>
{
    option.CheckConsentNeeded = context => false;
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();

    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
else
{
    app.UseExceptionHandler("/Home/Error");
}
//app.Services.GetService<IServiceHelper>()!.GetServices();

app.UseHttpsRedirection();
app.UseStaticFiles();


app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCookiePolicy();


app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
